package com.xcjh.module_ws.websocket

import android.annotation.SuppressLint
import android.content.*
import android.os.IBinder
import android.util.Log
import com.xcjh.base_lib.utils.*
import com.xcjh.module_ws.websocket.bean.ChatMsgBean
import com.xcjh.module_ws.websocket.bean.ReceiveReadWsBean
import com.xcjh.module_ws.websocket.bean.ReceiveWsBean
import com.xcjh.module_ws.websocket.listener.LiveRoomListener
import com.xcjh.module_ws.websocket.listener.LoginOrOutListener
import com.xcjh.module_ws.websocket.listener.C2CListener
import com.xcjh.module_ws.R
import com.xcjh.module_ws.websocket.listener.WsListener
import org.java_websocket.client.WebSocketClient
import java.util.*


/**
 * @author zobo101
 * 管理 webSocket
 */
class MyWsManager private constructor(private val mContext: Context) {

    val tag = "MyWsManager"

    companion object {

        @SuppressLint("StaticFieldLeak")
        private var INSTANCE: MyWsManager? = null
        fun getInstance(context: Context): MyWsManager? {
            if (INSTANCE == null) {
                Log.e("====", "getInstance: ===" + null)
                synchronized(MyWsManager::class.java) {
                    if (INSTANCE == null) {
                        INSTANCE = MyWsManager(context)
                    }
                }
            }
            Log.e("====", "getInstance: ===!==" + null)
            return INSTANCE
        }
    }

    private var serviceIntent: Intent? = null
    private var client: WebSocketClient? = null
    private var binder: MyWsClientService.WsClientBinder? = null
    private var service: MyWsClientService? = null
    private var receiver: ChatMessageReceiver? = null


    /**
     * 1.先初始化
     */
    fun initService() {
        try {
            if (service == null) {
                startJWebSClientService()
                doRegisterReceiver()
            }
        } catch (e: Exception) {
            Log.e(tag, "=======--initService------- ${e.message}")
        }
    }

    /**
     * 断开重连后同步数据
     */
    private fun asyncInfo() {

    }

    /**
     *
     */
    fun stopService() {
        try {
            mContext.stopService(serviceIntent)
            mContext.unbindService(serviceConnection)
            mContext.unregisterReceiver(receiver)

            serviceIntent = null
            client = null
            binder = null
            service = null
            receiver = null
            INSTANCE=null

        } catch (e: Exception) {
            Log.e("===", "stopService: ===" + e.message)
        }
    }

    /**
     * 启动服务（webSocket客户端服务）
     */
    private fun startJWebSClientService() {
        if (serviceIntent == null) {
            serviceIntent = Intent(mContext, MyWsClientService::class.java)
        }
        mContext.startService(serviceIntent)
        // 绑定服务
        mContext.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    /**
     * 动态注册广播
     */
    private fun doRegisterReceiver() {
        if (receiver == null) {
            receiver = ChatMessageReceiver()
        }
        val filter = IntentFilter(WebSocketAction.WEB_ACTION)
        mContext.registerReceiver(receiver, filter)
    }

    /**
     * 绑定服务与活动
     */
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            Log.e(tag, "=====服务与活动成功绑定")
            if (iBinder is MyWsClientService.WsClientBinder) {
                binder = iBinder
                service = binder?.service
                client = service?.client
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            Log.e(tag, "====服务与活动成功断开")
            service = null
            client = null
        }
    }

    private inner class ChatMessageReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val msg = intent?.getStringExtra("message") ?: return
            Log.e(tag, "onReceive======message------------  $msg")
            try {
                mWsListener.forEach {
                    val wsBean = jsonToObject2<ReceiveWsBean<Any>>(msg)
                    if (wsBean?.command!=13){
                        it.toPair().second.onReceive(msg)
                    }
                }
                parsingServiceLogin(msg)
            } catch (e: Exception) {
                Log.e(tag, "======onReceive===webSocket解析异常------------  ${e.message}")
            }
        }
    }

    /**
     * command
     *  5->6 登录成功         22->22 注销成功
     *  7->9 加入群聊成功       21->10 退出群聊成功
     *  13->13 心跳包成功
     *
     *
     *  11->12->11 发送消息->发送消息成功->接收到消息
     *  19->20 获取指定群聊或好友历史或离线消息成功
     *  23->23 消息已读回复
     */
    private fun parsingServiceLogin(msg: String) {
//{"command":13,"data":{"hbbyte":-128}}
        val wsBean = jsonToObject2<ReceiveWsBean<Any>>(msg)
        if (wsBean?.code == "10000") {
            when (wsBean.command) {
                6 -> {
                    mLoginOrOutListener?.onLoginIn(true, wsBean)
                }
                22 -> {
                    mLoginOrOutListener?.onLoginOut(true, wsBean)
                }
                9 -> {
                    mLiveRoomListener?.onEnterRoomInfo(true, wsBean)
                }
                10 -> {
                    mLiveRoomListener?.onExitRoomInfo(true, wsBean)
                }
                13 -> {
                    //心跳包成功

                }

                11 -> {
                    val bean = jsonToObject2<ReceiveWsBean<ChatMsgBean>>(msg)
                    val chatMsgBean = bean?.data
                    if (chatMsgBean?.chatType == 1) {
                        //群聊
                        mLiveRoomListener?.onRoomReceive(chatMsgBean)
                    } else {
                        //单聊
                        mC2CListener?.onC2CReceive(chatMsgBean!!)
                    }
                }
                20 -> {
                    val s = wsBean.data as String
                    val string2map = string2map<ChatMsgBean>(s)
                    string2map?.keys
                    string2map?.values
                }
                else -> {

                }
            }
        } else {
            val wsBean2 = jsonToObject2<ReceiveReadWsBean>(msg)
            if (wsBean2?.cmd == 23) {
                //消息已读回复

            } else {
                myToast(mContext.getString(R.string.ws_send_error))
            }
            // 登录过期
            mContext.let {
                // LoginAndOutUtil().logoutClick(it)
            }
        }

    }

    fun sendMessage(msg: String) {
        if (client?.isOpen == true) {
            msg.loge("===sendMessage==")
            service?.sendMsg(msg)
        }
    }

    private var mLoginOrOutListener: LoginOrOutListener? = null
    private var mLiveRoomListener: LiveRoomListener? = null
    private var mC2CListener: C2CListener? = null
    private val mWsListener = linkedMapOf<String,WsListener>()


    fun setLoginOrOutListener(listener: LoginOrOutListener) {
        this.mLoginOrOutListener = listener
    }

    fun setLiveRoomListener(listener: LiveRoomListener) {
        this.mLiveRoomListener = listener
    }

    fun setC2CListener(listener: C2CListener) {
        this.mC2CListener = listener
    }
    fun setWsListener(tag: String,listener: WsListener) {
        mWsListener[tag] = listener
    }
    /**
     * remove listener
     */
    fun removeWsListener(tag: String) {
        if (mWsListener[tag] !=null) {
            mWsListener.remove(tag)
        }
    }
}